//
//  Status.swift
//  weibopush
//
//  Created by 龚欣 on 15/6/30.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import SDWebImage
//import SVProgressHUD

class Status: NSObject {
    ///  MARK: 微博创建时间
    var created_at : String?
    /// MARK: 微博ID
    var id : Int = 0
    /// MARK: 微博内容
    var text : String?
    /// MARK : 微博来源
    var source : String?{
        didSet{
            sourceText = source?.hreflink().text ?? ""
        }
    }
    
    var sourceText : String?
    
    /// MARK : 缩略图数组
    var pic_urls : [[String : String]]?  {
        didSet{
           imageURLS = [NSURL]()
            largeImageURLS = [NSURL]()
            for dict in pic_urls!{
                 imageURLS?.append(NSURL(string: dict["thumbnail_pic"]!)!)
                
                var urlstring = dict["thumbnail_pic"]
                urlstring = urlstring?.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
               largeImageURLS?.append(NSURL(string: urlstring!)!)
                
            }
        }
    }
   private var imageURLS : [NSURL]?
    
    var pictureURLS : [NSURL]?{
        return retweeted_status != nil ? retweeted_status?.imageURLS : imageURLS
    }
    
   private var largeImageURLS : [NSURL]?
    
    var largePicURLS : [NSURL]?{
       
        return retweeted_status != nil ? retweeted_status?.largeImageURLS : largeImageURLS
    }
    
    
     /// MARK : 用户模型
    var user : User?
    
    /// MARK: 转发模型
    var retweeted_status : Status?
    
    let properties = ["created_at","id","text","source","pic_urls","user","retweeted_status"]
    
    /// MARK: 网络加载数据方法
    class func loadSinaData(since_id : Int, max_id : Int,finished : (statusList : [Status]?,error : NSError?)->()){
    
        StatusDAL.loadStatus(since_id, max_id: max_id) { (array, error) -> () in
            
            if error != nil {
                finished(statusList: nil, error: error)
                return
            }
            
            if array == nil {
                finished(statusList: nil, error: nil)
            }

            let list = analyseStatusData(array!)
        
            imageCaches(list, finished: finished)

        }
        
    }
    
    // MARK:返回数据的字典转模型
    private class func analyseStatusData(statues : [[String : AnyObject]]) -> [Status]{
    
        var arrayM = [Status]()
     
        for dict in statues{
            
            arrayM.append(Status(dict: dict))
        }
        
        return arrayM
    }
    
    //  MARK: 通过KVC 转模型 下面3个方法完成字典转模型，并不需要属性的列表
    init(dict : [String : AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if key == "user"{
            if let useDict = value as? [String : AnyObject]{
                user = User(dict: useDict)
            }
            return
        }
        if key == "retweeted_status"{
            if let retweetedDict = value as? [String : AnyObject]{
                retweeted_status = Status(dict: retweetedDict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    
    
    // MARK: 缓存缩略图
    class func imageCaches( list : [Status]?,finished : (statusList : [Status]?,error : NSError?)->()){
        
    let group = dispatch_group_create()
    
    for s in list!{
        
        if s.pictureURLS == nil || s.pictureURLS!.isEmpty {
            //continue 如果上面条件不满足就直接下次循环了，下面的代码不会执行了
           continue
        }
        
        for URL in s.pictureURLS!{
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(URL, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                dispatch_group_leave(group)
            })
        }
        
    }
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            // 完成回调
            finished(statusList: list, error: nil)
//            list = nil
        }
    
    }
    
   override var description : String {
    
        let dict = dictionaryWithValuesForKeys(properties)
        return "\(dict)"
    }
}
